<template>
  <div>
      <input type="text" v-maxlength='10' v-model="ipt">
      <textarea v-maxlength='20' v-model="text" cols="30" rows="10"></textarea>
      <Ipt type='input' maxlength='20'/>
  </div>
</template>

<script>
import Ipt from "@/components/Ipt";
export default {
  data() {
    return {
      ipt: "",
      text: ""
    };
  },
  directives: {
    maxlength: {
      inserted(el, binding) {
        let divDom = document.createElement("div");
        let spanDom = document.createElement("span");
        let parentWp = el.parentNode;

        parentWp.replaceChild(divDom, el);
        divDom.appendChild(el);
        divDom.appendChild(spanDom);

        divDom.style = "position: relative;display: inline-block;";
        spanDom.innerHTML = `0/${binding.value}`;
        if (el.tagName == "TEXTAREA") {
          spanDom.style = "position: absolute;bottom: 5px;right: 5px;";
        } else {
          spanDom.style =
            "position: absolute;top: 50%;right: 5px;transform: translate(0,-50%)";
        }

        el.setAttribute("maxlength", binding.value);
      },
      update(el, binding) {
        let next = el.nextElementSibling;
        let iptValLen = el.value.length;

        next.innerHTML = `${iptValLen}/${binding.value}`;

        if (iptValLen == binding.value) {
          el.style.color = "red";
        } else {
          el.style.color = "";
        }
      }
    }
  },
  components: {
    Ipt
  }
};
</script>

<style scoped>
.div {
  position: relative;
  display: inline-block;
}

.span {
  position: absolute;
  top: 50%;
  right: 2%;
  transform: translate(-50%);
}
</style>
